/**
 * 
 */
package com.sc.softmgr.business.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.acc.softmgr.model.SoftmgrProject;
import com.acc.softmgr.model.SoftmgrSubSystem;
import com.acc.softmgr.model.SoftmgrSubSystemExample;
import com.acc.softmgr.model.SoftmgrSystem;
import com.acc.softmgr.model.SysUser;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sc.softmgr.business.service.ISoftmgetProjectFeignService;
import com.sc.softmgr.business.service.ISoftmgrSubSystemService;
import com.sc.softmgr.business.service.ISoftmgrSystemFeignService;
import com.sc.softmgr.common.constant.DeleteStatus;
import com.sc.softmgr.common.constant.enums.RestStatus;
import com.sc.softmgr.common.utils.date.DateBase;
import com.sc.softmgr.common.web.DataGridObject;

/**
 * 
 * @content
 * 
 * @date 2017年5月8日
 * 
 * @author OprCalf
 * 
 */
@Controller
@RequestMapping("softSubSystem")
public class SoftmgrSubSystemController {

	private static Map<Integer, SoftmgrProject> projectMap = new HashMap<Integer, SoftmgrProject>();

	private static Map<Integer, SoftmgrSystem> systemMap = new HashMap<Integer, SoftmgrSystem>();

	@Autowired
	private ISoftmgetProjectFeignService softmgetProjectFeignService;

	@Autowired
	private ISoftmgrSystemFeignService softmgrSystemFeignService;

	@Autowired
	private ISoftmgrSubSystemService softmgrSubSystemService;

	@RequestMapping(value = "toSoftSubSystem", method = RequestMethod.GET)
	public String toSoftSubSystem() {
		return "softSubSystem/softSubSystem";
	}

	/**
	 * 查询列表页
	 * 
	 * @param project_name
	 * @param project_english
	 * @param page
	 * @param rows
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "searchSoftSubSystem", method = RequestMethod.GET)
	@ResponseBody
	public DataGridObject<SoftmgrSubSystem> searchSoftSubSystem(
			@RequestParam(value = "searchProjectId", required = false) String searchProjectId,
			@RequestParam(value = "searchSystemId", required = false) String searchSystemId,
			@RequestParam(value = "searchSubSystemName", required = false) String searchSubSystemName,
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "rows", required = false) Integer rows) throws Exception {

		List<SoftmgrSystem> listSystem = null;
		List<SoftmgrSubSystem> listSubSystem = null;

		if (StringUtils.isNotEmpty(searchProjectId)) {
			listSystem = getSoftmgrSystem(Integer.valueOf(searchProjectId));
			if (StringUtils.isNotEmpty(searchSystemId)) {
				listSubSystem = getSoftmgrSubSystem(searchSystemId, searchSubSystemName, page, rows);
			} else {
				listSubSystem = getSoftmgrSubSystem(listSystem, searchSubSystemName, page, rows);
			}

		} else {
			if (StringUtils.isNotEmpty(searchSystemId)) {
				listSubSystem = getSoftmgrSubSystem(searchSystemId, searchSubSystemName, page, rows);
			} else {
				listSubSystem = getSoftmgrSubSystem(searchSystemId, searchSubSystemName, page, rows);
			}
		}

		DataGridObject<SoftmgrSubSystem> responseObject = new DataGridObject<SoftmgrSubSystem>();
		for (SoftmgrSubSystem softmgrSubSystem : listSubSystem) {
			SoftmgrSystem softmgrSystem = this.cacheSoftmgrSystem(softmgrSubSystem.getSystem_id());
			softmgrSubSystem.setCreateTimestring(
					DateBase.formatDate(softmgrSubSystem.getCreatetime(), DateBase.DATE_PATTERN_DATETIME));
			softmgrSubSystem.setSystemName(softmgrSystem.getSystem_name());
			softmgrSubSystem.setProjectName(this.cacheSoftmgrProject(softmgrSystem.getProject_id()).getProject_name());

		}
		responseObject.setTotal(page * rows);
		responseObject.setRows(listSubSystem);
		projectMap.clear();
		return responseObject;
	}

	/**
	 * 新增子系统
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/addSoftSubSystem", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject addSoftSubSystem(@RequestParam String project_id, @RequestParam String system_id,
			@RequestParam String sub_system_name, HttpServletRequest request) throws Exception {
		JSONObject json = new JSONObject();
		SysUser currentUser = (SysUser) request.getSession().getAttribute("currentUser");
		if (StringUtils.isEmpty(project_id) || StringUtils.isEmpty(system_id) || StringUtils.isEmpty(sub_system_name)) {
			json.put("status", RestStatus.PARAMETER_REQUIRED.code);
			json.put("message", RestStatus.PARAMETER_REQUIRED.message);
			return json;
		} else {
			// ----------判断唯一性------------
			boolean exitSubSystem = exitSoftmgrSubSystem(system_id, sub_system_name);
			if (exitSubSystem) {
				json.put("status", RestStatus.NOT_UNIQUE.code);
				json.put("message", RestStatus.NOT_UNIQUE.message);
				return json;
			} else {
				SoftmgrSubSystem softmgrSubSystem = new SoftmgrSubSystem();
				softmgrSubSystem.setCreatetime(new Date());
				softmgrSubSystem.setCreateby(currentUser.getUsername());
				softmgrSubSystem.setSystem_id(Integer.valueOf(system_id));
				softmgrSubSystem.setSub_system_name(sub_system_name);
				softmgrSubSystem.setDeleted(DeleteStatus.FALSE);
				softmgrSubSystemService.insert(softmgrSubSystem);
				json.put("status", RestStatus.SUCCESS.code);
				json.put("message", RestStatus.SUCCESS.message);
				return json;
			}

		}

	}

	/**
	 * 修改子系统
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "editSoftSubSystem", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject editSoftSubSystem(@RequestParam("id") Integer id, @RequestParam("systemId") String systemId,
			@RequestParam("subSystemName") String subSystemName, HttpServletRequest request) throws Exception {
		JSONObject json = new JSONObject();
		SysUser currentUser = (SysUser) request.getSession().getAttribute("currentUser");
		if (StringUtils.isEmpty(systemId) || StringUtils.isEmpty(subSystemName) || id == null || id == 0) {
			json.put("status", RestStatus.PARAMETER_REQUIRED.code);
			json.put("message", RestStatus.PARAMETER_REQUIRED.message);
			return json;
		} else {
			// ----------判断唯一性------------

			boolean exitSubSystem = exitSoftmgrSubSystem(systemId, subSystemName);
			if (exitSubSystem) {
				json.put("status", RestStatus.NOT_UNIQUE.code);
				json.put("message", RestStatus.NOT_UNIQUE.message);
				return json;
			} else {
				SoftmgrSubSystem softmgrSubSystem = softmgrSubSystemService.selectByPrimaryKey(id);
				softmgrSubSystem.setSystem_id(Integer.valueOf(systemId));
				softmgrSubSystem.setSub_system_name(subSystemName);
				softmgrSubSystem.setUpdateby(currentUser.getUsername());
				softmgrSubSystem.setUpdatetime(new Date());
				softmgrSubSystemService.updateByPrimaryKey(softmgrSubSystem);
				json.put("status", RestStatus.SUCCESS.code);
				json.put("message", RestStatus.SUCCESS.message);
				return json;
			}

		}

	}

	/**
	 * 查询详情
	 * 
	 * @param id
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/{id}/searchSoftSubSystem", method = RequestMethod.GET)
	@ResponseBody
	public JSONObject searchSoftSubSystem(@PathVariable Integer id) throws Exception {
		JSONObject json = new JSONObject();
		if (id == null || id == 0) {
			json.put("status", RestStatus.PARAMETER_REQUIRED.code);
			json.put("message", RestStatus.PARAMETER_REQUIRED.message);
			return json;
		}
		SoftmgrSubSystem softmgrSubSystem = softmgrSubSystemService.selectByPrimaryKey(id);
		softmgrSubSystem.setProject_id(this.cacheSoftmgrSystem(softmgrSubSystem.getSystem_id()).getProject_id());
		softmgrSubSystem.setHiddenSystemId(String.valueOf(softmgrSubSystem.getSystem_id()));
		json.put("status", RestStatus.SUCCESS.code);
		json.put("message", RestStatus.SUCCESS.message);
		json.put("data", softmgrSubSystem);
		return json;
	}

	/**
	 * 删除子系统
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/removeSoftSubSystem", method = RequestMethod.POST)
	@ResponseBody
	public JSONObject removeSoftSubSystem(@RequestParam Integer id) throws Exception {
		JSONObject json = new JSONObject();
		if (id == null || id == 0) {
			json.put("status", RestStatus.PARAMETER_REQUIRED.code);
			json.put("message", RestStatus.PARAMETER_REQUIRED.message);
			return json;
		}
		SoftmgrSubSystem SoftmgrSubSystem = softmgrSubSystemService.selectByPrimaryKey(id);
		SoftmgrSubSystem.setDeleted(DeleteStatus.TRUE);
		softmgrSubSystemService.updateByPrimaryKey(SoftmgrSubSystem);
		json.put("status", RestStatus.SUCCESS.code);
		json.put("message", RestStatus.SUCCESS.message);
		return json;
	}

	/**
	 * 获取所有子系统
	 * 
	 * @return
	 */
	@RequestMapping(value = "getSoftSubSystem", method = RequestMethod.GET)
	@ResponseBody
	public String getSoftSubSystem() throws Exception {

		SoftmgrSubSystemExample example = new SoftmgrSubSystemExample();
		example.getCriteria().andDeletedEqualTo(DeleteStatus.FALSE);

		List<SoftmgrSubSystem> list = softmgrSubSystemService.selectByExample(example);
		JSONArray jsonArray = new JSONArray();
		for (SoftmgrSubSystem subSystem : list) {
			JSONObject json = new JSONObject();
			json.put("id", subSystem.getId());
			json.put("text", subSystem.getSub_system_name());
			jsonArray.add(json);
		}

		return jsonArray.toJSONString();
	}

	/**
	 * 判断是否存在子系统
	 * 
	 * @param systemId
	 * @param subSystemName
	 * @return
	 */
	private boolean exitSoftmgrSubSystem(String systemId, String subSystemName) {
		SoftmgrSubSystemExample example = new SoftmgrSubSystemExample();
		example.getCriteria().andSystem_idEqualTo(Integer.valueOf(systemId));
		example.getCriteria().andSub_system_nameEqualTo(subSystemName);
		example.getCriteria().andDeletedEqualTo(DeleteStatus.FALSE);
		List<SoftmgrSubSystem> SoftmgrSubSystems = softmgrSubSystemService.selectByExample(example);
		if (SoftmgrSubSystems != null && SoftmgrSubSystems.size() > 0) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * 根据项目ID获取系统
	 * 
	 * @param projectId
	 * @return
	 */
	private List<SoftmgrSystem> getSoftmgrSystem(Integer projectId) {
		return softmgrSystemFeignService.getSoftSystems(projectId);
	}

	/**
	 * 根据系统id跟子系统名称获取子系统列表
	 * 
	 * @param systemId
	 * @param subSystemName
	 * @return
	 */
	private List<SoftmgrSubSystem> getSoftmgrSubSystem(String systemId, String searchSubSystemName, Integer page,
			Integer rows) {
		SoftmgrSubSystemExample listSubSystemExample = new SoftmgrSubSystemExample();
		listSubSystemExample.getCriteria().andDeletedEqualTo(DeleteStatus.FALSE);
		if (StringUtils.isNotEmpty(systemId)) {
			listSubSystemExample.getCriteria().andSystem_idEqualTo(Integer.valueOf(systemId));
		}
		if (!StringUtils.isEmpty(searchSubSystemName)) {
			listSubSystemExample.getCriteria().andSub_system_nameLike("%" + searchSubSystemName + "%");
		}
		if (page == null || page == 0) {
			page = 1;
		}
		listSubSystemExample.setCount(page * rows);
		listSubSystemExample.setLimitStart((page - 1) * rows);
		return softmgrSubSystemService.selectByExample(listSubSystemExample);
	}

	/**
	 * 根据系统id跟子系统名称获取子系统列表
	 * 
	 * @param systemId
	 * @param subSystemName
	 * @return
	 */
	private List<SoftmgrSubSystem> getSoftmgrSubSystem(List<SoftmgrSystem> listSystem, String searchSubSystemName,
			Integer page, Integer rows) {
		List<Integer> ids = new ArrayList<Integer>();
		for (SoftmgrSystem softmgrSystem : listSystem) {
			ids.add(softmgrSystem.getId());
		}
		SoftmgrSubSystemExample listSubSystemExample = new SoftmgrSubSystemExample();
		listSubSystemExample.getCriteria().andDeletedEqualTo(DeleteStatus.FALSE);
		listSubSystemExample.getCriteria().andSystem_idIn(ids);
		if (!StringUtils.isEmpty(searchSubSystemName)) {
			listSubSystemExample.getCriteria().andSub_system_nameLike("%" + searchSubSystemName + "%");
		}
		if (page == null || page == 0) {
			page = 1;
		}
		listSubSystemExample.setCount(page * rows);
		listSubSystemExample.setLimitStart((page - 1) * rows);
		return softmgrSubSystemService.selectByExample(listSubSystemExample);
	}

	/**
	 * 缓存SoftmgrSystem对象
	 */
	private SoftmgrSystem cacheSoftmgrSystem(Integer id) {
		SoftmgrSystem softmgrSystem = systemMap.get(id);
		if (softmgrSystem == null) {
			JSONObject json = softmgrSystemFeignService.searchSoftSystem(id);
			if (!"500".equals(json.get("status"))) {
				softmgrSystem = json.getObject("data", SoftmgrSystem.class);
				systemMap.put(id, softmgrSystem);
				softmgrSystem = systemMap.get(id);
			}

		}
		return softmgrSystem;

	}

	/**
	 * 缓存SoftmgrProject对象
	 */
	private SoftmgrProject cacheSoftmgrProject(Integer id) {
		SoftmgrProject softmgrProject = projectMap.get(id);
		if (softmgrProject == null) {
			JSONObject json = softmgetProjectFeignService.searchSoftProject(id);
			if (!"500".equals(json.get("status"))) {
				softmgrProject = json.getObject("data", SoftmgrProject.class);
				projectMap.put(id, softmgrProject);
				softmgrProject = projectMap.get(id);
			}
		}
		return softmgrProject;

	}

}
